using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Colorful.CMS.Core;
using Microsoft.Extensions.FileProviders;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Razor;
using System.Runtime.Loader;
using Microsoft.Extensions.Options;
using Colorful.Database;
using Colorful.Models;
using Microsoft.AspNetCore.SpaServices.Webpack;

namespace Colorful.CMS
{
    public class Startup : ColorCmsStartup
    {
        public Startup(IConfiguration configuration) : base(configuration)
        {
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            base.ConfigureServices(services);
            services.AddCors(options =>
            {
                options.AddPolicy("*",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowAnyHeader().AllowCredentials());
            });
            this.MvcBuilder.AddMvcOptions(options =>
            {
                options.Filters.Add(new APIAuthFilter());
            });
            //Todo
            //var dllPath = WebService.RootPath + "\\plugins\\Guestbook.dll";
            //var assembly = Assembly.LoadFile(dllPath);
            //this.MvcBuilder.AddApplicationPart(assembly);
            //var embeddedProvider = new EmbeddedFileProvider(assembly);
            //services.Configure<RazorViewEngineOptions>(options =>
            //{
            //    options.FileProviders.Add(embeddedProvider);
            //});
        }

        public override void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            base.Configure(app, env, loggerFactory);
            app.UseCors("*");
            if (env.IsDevelopment())
            {
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            WebService.AdminViewCallbacks.Add("Home/Index", controller =>
            {
                using (var db = CMSDbHelper.GetDb())
                {
                    var todayStat = db.StatByDates.FirstOrDefault(a => a.Id == $"UV{DateTime.Now.ToString("yyyyMMdd")}");
                    if (todayStat == null)
                        todayStat = new StatByDate() { UV = 0, IP = 0, PV = 0, NU = 0 };

                    controller.ViewData["Icons"] = new object[]
                    {
                        new { icon = "icon-user", color= "#4DA1FF", title = $"{todayStat.UV}", subTitle = "今日访问(UV)" },
                        new { icon = "icon-gaoshouyi", color= "#FFCD31", title = $"{todayStat.PV}", subTitle = "今日流量(PV)" },
                        new { icon = "icon-user-two", color= "#83D587", title = $"{todayStat.NU}", subTitle = "今日新增" },
                        new { icon = "icon-doc", color= "#9587F1", title = $"{todayStat.IP}", subTitle = "注册会员" },
                    };
                }
            });
        }

        public override void LoadSettings(bool reload = false)
        {
            base.LoadSettings(reload);

            var appSetting = Configuration.GetSection("AppSetting");
            MyWebService.NodeJsAPIUrl = appSetting.GetValue<string>("NodeAPIUrl");
            if (string.IsNullOrEmpty(MyWebService.NodeJsAPIUrl))
                MyWebService.NodeJsAPIUrl = "http://localhost:3570";
            if (!MyWebService.NodeJsAPIUrl.EndsWith("/"))
                MyWebService.NodeJsAPIUrl += "/";
            MyWebService.PythonAPIUrl = appSetting.GetValue<string>("PythonAPIUrl");
            if (string.IsNullOrEmpty(MyWebService.PythonAPIUrl))
                MyWebService.PythonAPIUrl = MyWebService.NodeJsAPIUrl.Replace(":3570", ":3571");
        }
    }
}
